package com.sixth.docker.controller;

import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.A;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sixth.core.entity.Patient;
import com.sixth.core.entity.PatientFile;
import com.sixth.core.vo.R;
import com.sixth.docker.service.PatientFileService;
import com.sixth.docker.service.PatientService;
import com.sixth.docker.vo.PatientVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Random;

/**
 * @program: sixth-hospital-parent
 * @description:
 * @author: 赵庆龙
 * @create: 2024-08-15 10:41
 **/
@RestController
@RequestMapping("/doctor/registered")
public class PatientController {
    @Autowired
    private PatientService patientService;
    @Autowired
    private PatientFileService patientFileService;
    @GetMapping("/selectByCard/{idcard}")
    public R<Patient> selectByCard(@PathVariable String idcard)
    {
        return patientService.selectByCard(idcard);
    }

//添加信息
    @ApiOperation("添加信息")
    @PostMapping("/insert")
    public R<Patient> insertOrUpdate(@RequestBody Patient patient){
        String prefix = "HZ";  // 定义前缀
        long timestamp = System.currentTimeMillis();  // 获取当前时间戳
        Random random = new Random();
        int randomNumber = random.nextInt(1000000);  // 生成随机数

        // 先尝试根据身份证号查找现有记录
        R<Patient> existingPatientResponse = patientService.selectByCard(patient.getIdCard());
        Patient existingPatient = existingPatientResponse.getData();

        if (existingPatient != null) {
            // 更新现有记录的字段
            existingPatient.setName(patient.getName());
            existingPatient.setPhone(patient.getPhone());
            existingPatient.setSex(patient.getSex());
            existingPatient.setAddress(patient.getAddress());
            existingPatient.setBirthday(patient.getBirthday());
            return patientService.update(existingPatient); // 假设你有一个更新方法在service层
        } else {
            // 如果不存在，设置新的patient ID，并插入新记录
            patient.setPatientId(prefix + timestamp + String.format("%06d", randomNumber));
            return patientService.insert(patient);
        }
    }
    @GetMapping("/selectByPatientId/{patientId}")
    public R<Patient> selectByPatientId(@PathVariable String patientId) {
        patientFileService.insertOrUpdate(patientId);
        // 返回患者信息
        return patientService.selectByPatientId(patientId);
    }
    @ApiOperation(value = "分页查找")
    @PostMapping("/selectByPage")
    public R<IPage<Patient>> selectByPage(@RequestBody PatientVo patientVo) {
        return patientService.selectByPage(patientVo);
    }

    @GetMapping("/selectById/{patientId}")
    public R<Patient> selectById(@PathVariable String patientId) {
        return patientService.selectByPatientId(patientId);
    }
}
